<template>
  <div class="echart-container">
    <div id="myChart" style="width: 800px;height:500px;"></div>
  </div>
</template>

<script>
import echarts from 'echarts'

export default {
  name: 'Echart',
  props: {
    xAxis: {
      type: Array,
      default: () => []
    },
    rcvTableData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    rcvTableData: {
      handler() {
        this.initChart()
      },
      deep: true
    },
    xAxis: {
      handler() {
        this.initChart()
      },
      deep: true
    }
  },
  mounted() {
    this.initChart()
  },
  methods: {
    processData() {
      // 获取所有不重复的 trainNo
      const trainNos = [...new Set(this.rcvTableData.map(item => item.trainNo))]

      // 按 trainNo 分组统计数据
      const result = trainNos.map(trainNo => {
        return {
          name: trainNo,
          type: 'bar',
          data: this.xAxis.map(chartItem => {
            return this.rcvTableData.filter(mockItem =>
              mockItem.alarmLabel === chartItem.value.toString() &&
              mockItem.trainNo === trainNo
            ).length
          })
        }
      })

      return result
    },
    initChart() {
      this.chart = echarts.init(document.getElementById('myChart'))
      const seriesData = this.processData()
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          textStyle: {
            color: '#ffffff',
          },
          data: seriesData.map(item => item.name)
        },
        xAxis: {
          type: 'category',
          data: this.xAxis.map(item => item.description),
          axisLabel: {
          color: '#ffffff',
          interval: 0,  // 强制显示所有标签
          rotate: 20    // 标签旋转30度，防止重叠
        }

        },
        yAxis: {
          type: 'value',
          axisLabel: {
          color: '#ffffff'  // y轴文字颜色
        },

        },
        series: seriesData.map((item, index) => ({
          name: item.name,
          type: 'bar',
          data: item.data,
          itemStyle: {
            color: [
              '#5470c6',
              '#91cc75',
              '#fac858',
              '#73c0de',
              '#3ba272',
              '#fc8452',
              '#9a60b4'
            ][index]
          }
        }))
      }

      this.chart.setOption(option)
    }
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
    }
  }
}
</script>

<style scoped>
.echart-container {
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
